package com.zmj.mobile.controller;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.zmj.framework.response.Result;
import com.zmj.framework.util.StringUtil;
import com.zmj.mobile.entity.QuoteItemMainEntity;
import com.zmj.mobile.entity.SealApplyEntity;
import com.zmj.mobile.entity.TechPurMainEntity;
import com.zmj.mobile.service.IQuoteItemMainService;
import com.zmj.mobile.service.ISealApplyService;
import com.zmj.mobile.service.ITechPurMainService;
import io.swagger.v3.oas.annotations.Operation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.util.List;
import java.util.Map;

/**
 * @Description 本地接口 目的是不影响其他服务正常使用，用来操作本地数据和文件同步到正在使用的数据库中
 * @Author ChengShenzhen
 * @Date 11:26 2024/2/3 0003
**/
@Slf4j
@RestController
@RequestMapping("/v1/api/local")
public class LocalController {

    @Resource
    private ISealApplyService iSealApplyService;

    @Resource
    private IQuoteItemMainService quoteItemMainService;

    @Resource
    private ITechPurMainService techPurMainService;


    /**
     * @Description 导入用印申请
     * @Author ChengShenzhen
     * @Date 21:19 2024/2/1 0001
     **/
    @Operation(summary = "导入")
    @PostMapping("import")
    public Result<Object> importExcel(@RequestPart(value = "file") MultipartFile file, int sheet) {
        iSealApplyService.importExcel(file,sheet);
        return Result.success();
    }

    /**
     * @Description 附件下载 --本地一次性接口
     * @Author ChengShenzhen
     * @Date 11:24 2024/2/3 0003
     **/
    @GetMapping("/downloadFile")
    public Result<String> downloadFile(int end,String fileName,int sheet) {
        String filePath = "D:\\data\\mobile\\files\\";
        ExcelReader reader = ExcelUtil.getReader("D:\\data\\mobile\\"+fileName);
        reader.setSheet(sheet);
        int start = 1;
        int head = 0;
        reader.read(start, end, (cell, value) -> {
            if(cell==null){
                return;
            }
            if (cell.getHyperlink() != null) {
                cell.setCellValue(cell.getHyperlink().getAddress());
            }
        });
        List<Map<String, Object>> read = reader.read(head, start, end);
        for (Map<String, Object> stringObjectMap : read) {
            downLoadImg(stringObjectMap, "图片", filePath);
            downLoadImg(stringObjectMap, "附件", filePath);
            downLoadImg(stringObjectMap, "附件结果", filePath);
        }
        return Result.success();
    }

    private static void downLoadImg(Map<String, Object> stringObjectMap, String c, String filePath) {
        if (ObjectUtils.isEmpty(stringObjectMap.get(c))){
            return;
        }
        String object = stringObjectMap.get(c).toString();
        if (StringUtil.isNotBlank(object) && !"#VALUE!".equals(object)) {
            System.out.println(object);
            String s = object.split("key=")[1];
            JSONObject jsonObject;
            try (HttpResponse execute = HttpUtil.createPost("https://www.feishu.cn/approval/admin/api/attachment/listApprovalAttachment?locale=zh_cn")
                    .body("{\"key\":\"" + s + "\"}")
                    .cookie("passport_app_access_token=eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3MDY4MTg5NTUsInVuaXQiOiJldV9uYyIsInJhdyI6eyJtX2FjY2Vzc19pbmZvIjp7IjExOSI6eyJpYXQiOjE3MDY3NzU3NTUsImFjY2VzcyI6dHJ1ZX19LCJzdW0iOiI0ODE4ZjQ4ZjQ0YTBlNzRiMmFhZTEyNGU5NjhkZWY4NDFmMGE1YTc1YjBhNWY4N2ViOTliZTg3ZTkxOGNiNDAyIn19.2YVyVTqdHCOsNwL3LPHvtbMrcxYdRHt8PlhOx8iVTZT7v5giZJlxvNUW5mX9kOh7shwZxfU_U86rvn9eumNIOw; swp_csrf_token=7145c733-0bbf-4a66-9ed4-332d33d13f66;")
                    .execute()) {
                jsonObject = JSONUtil.parseObj(execute.body());
            }
            int i = 0;
            JSONArray jsonArray = jsonObject.getJSONObject("data").getJSONArray("attachmentWidget").getJSONObject(0).getJSONArray("attachements");
            int n  = 1;
            int size = jsonArray.size();
            for (Object o : jsonArray) {
                log.info("==================正在处理第: "+n+" 条数据==============,共计有： "+size+" 条数据");
                JSONObject jsonObject1 = JSONUtil.parseObj(o);
                String name = jsonObject1.getStr("name");
                String id = stringObjectMap.get("申请编号").toString();
                System.out.println(id);
                if (StringUtil.isBlank(name)) {
                    name = id + "_" + i++ + ".jpeg";
                }
                String url = jsonObject1.getStr("url");
                System.out.println(url);
                try (HttpResponse execute = HttpUtil.createGet(url)
                        .cookie("passport_app_access_token=eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3MDY4MTg5NTUsInVuaXQiOiJldV9uYyIsInJhdyI6eyJtX2FjY2Vzc19pbmZvIjp7IjExOSI6eyJpYXQiOjE3MDY3NzU3NTUsImFjY2VzcyI6dHJ1ZX19LCJzdW0iOiI0ODE4ZjQ4ZjQ0YTBlNzRiMmFhZTEyNGU5NjhkZWY4NDFmMGE1YTc1YjBhNWY4N2ViOTliZTg3ZTkxOGNiNDAyIn19.2YVyVTqdHCOsNwL3LPHvtbMrcxYdRHt8PlhOx8iVTZT7v5giZJlxvNUW5mX9kOh7shwZxfU_U86rvn9eumNIOw; swp_csrf_token=7145c733-0bbf-4a66-9ed4-332d33d13f66;")
                        .execute()) {
                    execute.writeBody(filePath + id + "\\" + name);
                }

            }
        }
    }

    /**
     * @Description 处理询价附件地址  --一次性本地接口
     * @Author ChengShenzhen
     * @Date 20:05 2024/2/2 0002
     **/
    @PostMapping("initQuoteItemPic")
    public void initQuoteItemPic(){
        String minioPath = "/mobile-audit/alldata/";
        String filePath = "D:\\data\\mobile\\datas\\alldata\\";
        //查询所有需要处理的数据
        List<QuoteItemMainEntity> list = quoteItemMainService.list();
        //根据申请单号查询附件
        for (int i = 0; i <list.size(); i++) {
            QuoteItemMainEntity quoteItemMainEntity = list.get(i);
            // 获取指定文件夹路径下的所有文件
            Long approveCode = quoteItemMainEntity.getId();
            File folder = new File(filePath+approveCode);
            if (folder.exists() && folder.isDirectory()) {
                File[] files = folder.listFiles();
                //拼接附件地址
                String attachmentPath = "";
                //拼接附件名称
                String attachment = "";
                for (File file : files) {
                    attachmentPath= attachmentPath+minioPath+approveCode+"/"+file.getName()+",";
                    attachment = attachment + file.getName()+",";
                }
                attachmentPath = attachmentPath.substring(0,attachmentPath.length()-1);
                attachment = attachment.substring(0,attachment.length()-1);
                quoteItemMainEntity.setAttachmentPath(attachmentPath);
                quoteItemMainEntity.setAttachment(attachment);
                log.info("附件名称："+attachment);
                log.info("附件地址："+attachmentPath);
                //修改用章申请附件地址
                quoteItemMainService.updateById(quoteItemMainEntity);
            } else {
                log.info("申请编号为："+approveCode+" 的单子没有附件");
            }
        }
    }

    /**
     * @Description 处理研发试制附件地址  --一次性本地接口
     * @Author ChengShenzhen
     * @Date 14:04 2024/2/3 0003
    **/
    @PostMapping("initTechPic")
    public void initTechPic(){

        String minioPath = "/mobile-audit/alldata/";
        String filePath = "D:\\data\\mobile\\datas\\alldata\\";
        //查询所有需要处理的数据
        List<TechPurMainEntity> list = techPurMainService.list();
        //根据申请单号查询附件
        for (int i = 0; i <list.size(); i++) {
            TechPurMainEntity techPurMainEntity = list.get(i);
            // 获取指定文件夹路径下的所有文件
            if (StringUtil.isBlank(techPurMainEntity.getApplyCode())){
                continue;
            }
            Long approveCode = Long.parseLong(techPurMainEntity.getApplyCode());
            File folder = new File(filePath+approveCode);
            if (folder.exists() && folder.isDirectory()) {
                File[] files = folder.listFiles();
                //拼接附件地址
                String attachmentPath = "";
                //拼接附件名称
                String attachment = "";
                for (File file : files) {
                    attachmentPath= attachmentPath+minioPath+approveCode+"/"+file.getName()+",";
                    attachment = attachment + file.getName()+",";

                }
                attachmentPath = attachmentPath.substring(0,attachmentPath.length()-1);
                attachment = attachment.substring(0,attachment.length()-1);
                techPurMainEntity.setAttachmentPath(attachmentPath);
                techPurMainEntity.setAttachment(attachment);
                log.info("附件名称："+attachment);
                log.info("附件地址："+attachmentPath);
                //修改用章申请附件地址
                techPurMainService.updateById(techPurMainEntity);
            } else {
                log.info("申请编号为："+approveCode+" 的单子没有附件");
            }
        }
    }

    /**
     * @Description 处理用章申请附件地址  --一次性本地接口
     * @Author ChengShenzhen
     * @Date 14:04 2024/2/3 0003
     **/
    @PostMapping("initSealPic")
    public void initSealPic(){
        String minioPath = "/mobile-audit/alldata/";
        String filePath = "D:\\data\\mobile\\datas\\alldata\\";
        //查询所有需要处理的数据
        List<SealApplyEntity> list = iSealApplyService.list();
        //根据申请单号查询附件
        for (int i = 0; i <list.size(); i++) {
            SealApplyEntity sealApplyEntity = list.get(i);
            // 获取指定文件夹路径下的所有文件
            Long approveCode = sealApplyEntity.getId();
            File folder = new File(filePath+approveCode);
            if (folder.exists() && folder.isDirectory()) {
                File[] files = folder.listFiles();
                //拼接附件地址
                String attachmentPath = "";
                String attachment = "";
                for (File file : files) {
                    attachmentPath= attachmentPath+minioPath+approveCode+"/"+file.getName()+",";
                    attachment = attachment + file.getName()+",";
                }
                attachmentPath = attachmentPath.substring(0,attachmentPath.length()-1);
                sealApplyEntity.setAttachmentPath(attachmentPath);
                attachment = attachment.substring(0,attachment.length()-1);
                sealApplyEntity.setAttachment(attachment);
                log.info("附件名称："+attachment);
                log.info("附件地址："+attachmentPath);
                //修改用章申请附件地址
                iSealApplyService.updateById(sealApplyEntity);
            } else {
                log.info("申请编号为："+approveCode+" 的单子没有附件");
            }
        }

    }


}
